// Copyright (c) 2024 Go-Frame-Lite
// Go-Frame-Lite is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//         http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

package main

import (
	"context"
	"os"
	"os/signal"
	"syscall"
	"time"

	"go-frame-lite/pkg/config"
	"go-frame-lite/pkg/logger"
	"go-frame-lite/pkg/server"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func main() {
	// 加载配置
	appConfig, err := config.LoadConfig("configs/config.yaml")
	if err != nil {
		panic(err)
	}

	// 初始化日志
	log, err := logger.NewLogger(appConfig.Log)
	if err != nil {
		panic(err)
	}
	defer log.Sync()

	// 创建服务器配置
	serverConfig := server.Config{
		Addr:         appConfig.Server.Addr,
		ReadTimeout:  appConfig.Server.ReadTimeout,
		WriteTimeout: appConfig.Server.WriteTimeout,
		IdleTimeout:  appConfig.Server.IdleTimeout,
		EnableWS:     appConfig.Server.EnableWS,
	}

	// 创建服务器（现在支持监控功能）
	srv := server.New(serverConfig, &appConfig.Monitor)

	// 获取Gin引擎
	engine := srv.Engine()

	// 添加示例路由
	engine.GET("/health", func(c *gin.Context) {
		c.JSON(200, gin.H{"status": "ok", "timestamp": time.Now().Unix()})
	})

	engine.POST("/api/data", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message":   "数据处理成功",
			"timestamp": time.Now().Unix(),
		})
	})

	engine.GET("/api/users/:id", func(c *gin.Context) {
		id := c.Param("id")
		c.JSON(200, gin.H{
			"user_id":   id,
			"name":      "示例用户",
			"timestamp": time.Now().Unix(),
		})
	})

	// 启动服务器
	go func() {
		if err := srv.Start(); err != nil {
			logger.Error(context.Background(), "服务器启动失败", zap.Error(err))
		}
	}()

	logger.Info(context.Background(), "应用启动成功", 
		zap.String("server_addr", appConfig.Server.Addr),
		zap.Bool("monitor_enabled", appConfig.Monitor.Enabled),
		zap.String("metrics_path", appConfig.Monitor.MetricsPath),
		zap.String("metrics_port", appConfig.Monitor.MetricsPort),
	)

	// 优雅关闭
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	logger.Info(context.Background(), "正在关闭服务器...")
	
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	
	if err := srv.Shutdown(ctx); err != nil {
		logger.Error(context.Background(), "服务器关闭失败", zap.Error(err))
	}
	
	logger.Info(context.Background(), "服务器已关闭")
}